<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Organization extends Model
{
    use HasChinaAreaTrait;

    protected $table = 'mckj_organization';

    protected $fillable = [
        'org_uid', 'org_type_id', 'name',
        'province_code', 'city_code', 'district_code',
        'address', 'company_tel'
    ];

    const CREATED_AT  = 'created_time';

    const UPDATED_AT = 'updated_time';

    public static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub

        static::deleted(function ($model) {
            $model->user()->delete();
            $model->carbarns()->detach();
        });
    }

    /**
     * 合作商拥有的洗车舱
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function carbarns()
    {
        return $this->belongsToMany(Carbarn::class, "mckj_organization_mcstation", "org_id", "cart_id")
            ->using(OrganizationCarbarn::class)->withTimestamps()->withPivot(['divided']);
    }

    /**
     * 合作商拥有的门店
     *
     * @return $this
     */
    public function stations()
    {
        return $this->belongsToMany(Station::class, "mckj_organization_mcstation", "org_id", "mcstation_id")
            ->using(OrganizationCarbarn::class)->withTimestamps();
    }

    public function user()
    {
        return $this->belongsTo(OrganizationUser::class, 'org_uid');
    }

    public function type()
    {
        return $this->belongsTo(OrganizationType::class, "org_type_id");
    }

}
